<?php

namespace app\api\controller;

use addons\epay\library\Service;
use app\common\controller\Api;
use app\common\model\Artificer;
use app\common\model\Category;
use app\common\model\mall\Coupon;
use app\common\model\mall\Goods;
use app\common\model\Pay;
use app\common\model\PayRefund;
use app\common\model\Store;
use think\Config;
use think\Db;
use think\Exception;
use think\Log;

/**
 * 首页接口
 */
class Index extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    /**
     * 首页
     *
     */
    public function index()
    {
        $this->success('请求成功');
    }

    /**
     * 配置信息    1：用户隐私协议
     * @return void
     */
    public function setting()
    {
        try {
            $type = $this->request->post('type');
            switch (intval($type)){
                case 1:
                    $name = 'privacy_agreement';
                    $group = 'user';
                    break;
                case 2:
                    $name = 'about_us';
                    $group = 'basic';
                    break;
                default:
                    throw new Exception('参数缺失');
            }
            $value = \app\common\model\Config::getValue($name,$group);
            $this->success('配置信息',$value);
        }catch (Exception $e){
            $this->error($e->getMessage());
        }
    }

    /**
     * 分类
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function category()
    {
        $type = $this->request->post('type');
        if(empty($type)){
            $this->error('参数type缺失');
        }
        $where = ['type' => ['=',$type],'status'=>['=','normal']];
        $status = $this->request->post('status');
        if(($type == 'goods') && isset($status) && $status){
            if(!in_array($status,['10','20'])){
                $this->error(__('Invalid parameters'));
            }
            $where['flag'] = ['=',$status];
        }
        $list = Category::where($where)->field('id,name')->order('weigh desc,id desc')->select();
        if(empty($list)){
            $this->error('暂无数据');
        }
        $this->success('分类',$list);
    }

    /**
     * 入驻费用
     * @return void
     */
    public function expenseInfo()
    {
        try {
            $arr = \app\common\model\Config::getValue('check-in fee','basic');
            $arr = arrayToDyadicArray($arr);
            $amount = array_sum(array_column($arr,'fee'));
            $this->success('success',['arr' => $arr, 'amount' => $amount]);
        }catch (Exception $e){
            $this->error($e->getMessage());
        }
    }

    /**
     * 优惠券列表，用于商家添加商品
     * @return void
     */
    public function couponList()
    {
        try {
            $list = Coupon::where(['starttime' => ['<',time()],'endtime'=>['>',time()],'switch'=>['=',1]])->order('weigh desc,id desc')->field('id,title')->select();
            $this->success('OK',$list);
        }catch (Exception $e){
            $this->error($e->getMessage());
        }
    }

    /**
     * 图片管理  Banner
     * @return void
     */
    public function bannerList()
    {
        try {
            $category_id = 14;
            $bannerList = model('app\admin\model\setting\Banner')->where('switch',1)->where('category_id',$category_id)->order('weigh desc,id desc')->field('name,image,type,url,content,url_type,parameter')->select();
            if($bannerList){
                foreach ($bannerList as $k=>&$v){
                    $v['image'] = $v['image'] ? cdnurl($v['image'],true) : '';
                }
            }
            $this->success('success',$bannerList);
        }catch (Exception $e){
            Log::write($e->getMessage(),'error',true);
            $this->success(__('Network error'));
        }
    }

    /**
     * @return void
     */
    public function notice()
    {
        try {
            $id = $this->request->post('id');
            if(empty($id)){
                $id = model('app\admin\model\setting\Notice')->where(['switch'=>['=',1]])->order('weigh desc,id desc')->value('id');
            }
            //展示最新的一条记录，或者  指定公告信息
            $info = model('app\admin\model\setting\Notice')->where('id',$id)->field('id,title,content')->find();
            $this->success('success',$info);
        }catch (Exception $e){
            Log::write($e->getMessage(),'error',true);
            $this->success(__('Network error'));
        }
    }

    /**
     * 公告列表
     * @return void
     */
    public function noticeList()
    {
        try {
            $list = model('app\admin\model\setting\Notice')->where(['switch'=>['=',1]])->order('weigh desc,id desc')->field('id,title,content')->select();
            $this->success('success',$list);
        }catch (Exception $e){
            Log::write($e->getMessage(),'error',true);
            $this->success(__('Network error'));
        }
    }

    /**
     * 店铺列表
     * @return void
     */
    public function storeList(){
        try {
            $limit = $this->request->post('limit/d');
            $page = $this->request->post('page/d');
            $category_id = $this->request->post('category_id'); //商家服务类目
            $search = $this->request->post('search'); //搜索
            $recommend_switch = $this->request->post('recommend_switch');   //热门  推荐
            $where = [];
            if($category_id){
                $where[] = ['exp',Db::raw("FIND_IN_SET('$category_id',category_ids)")];
            }
            if($search){
                $where['shop_name'] = ['LIKE', '%'.$search.'%'];
            }
            if($recommend_switch){
                $where['recommend_switch'] = ['=', 1];
            }
            $storeModel = new Store();
            $list = $storeModel->list($where,$limit,$page,true);
            if($list === false){
                $this->error($storeModel->getError());
            }
            $this->success(__('success'),$list);
        }catch (Exception $e){
            Log::write('错误信息：'.$e->getMessage(),'error',true);
            $this->error(__('Network error'));
        }
    }

    /**
     * 店铺详情
     * @return void
     */
    public function storeInfo(){
        try {
            $id = $this->request->post('id/d');
            $user_id = $this->auth->isLogin() ? $this->auth->id : null;
            $model = new Store();
            $data = $model->details($id,$user_id);
            if($data === false){
               $this->error($model->getError());
            }
            $this->success(__('success'),$data);
        }catch (Exception $e){
            Log::write('错误信息：'.$e->getMessage(),'error',true);
            $this->error(__('Network error'));
        }
    }

    /**
     * 商品列表
     * @return void
     */
    public function goodsList(){
        try {
            $limit = $this->request->post('limit/d');
            $page = $this->request->post('page/d');
            $category_id = $this->request->post('category_id'); //商品类目
            $search = $this->request->post('search'); //搜索
            $where = [];
            if($category_id){
                $where['category_id'] = ['=',$category_id];
            }
            if($search){
                $where['name'] = ['LIKE', '%'.$search.'%'];
            }
            $goodsModel = new Goods();
            $list = $goodsModel->list($where,$limit,$page,true);
            if($list === false){
                $this->error($goodsModel->getError());
            }
            $this->success(__('success'),$list);
        }catch (Exception $e){
            Log::write('错误信息：'.$e->getMessage(),'error',true);
            $this->error(__('Network error'));
        }
    }

    /**
     * 商品详情
     * @return void
     */
    public function goodsInfo(){
        try {
            $id = $this->request->post('id/d');
            $user_id = $this->auth->isLogin() ? $this->auth->id : null;
            $model = new Goods();
            $data = $model->details($id,$user_id);
            if($data === false){
                $this->error($model->getError());
            }
            $this->success(__('success'),$data);
        }catch (Exception $e){
            Log::write('错误信息：'.$e->getMessage(),'error',true);
            $this->error(__('Network error'));
        }
    }

    /**
     * 技工列表
     * @return void
     */
    public function artificerList(){
        try {
            $limit = $this->request->post('limit/d');
            $page = $this->request->post('page/d');
            $category_id = $this->request->post('category_id'); //技工经营业务类目
            $where = [];
            if($category_id){
                $where[] = ['exp',Db::raw("FIND_IN_SET('$category_id',category_ids)")];
            }
            $artificerModel = new Artificer();
            $list = $artificerModel->list($where,$limit,$page,true);
            if($list === false){
                $this->error($artificerModel->getError());
            }
            $this->success(__('success'),$list);
        }catch (Exception $e){
            Log::write('错误信息：'.$e->getMessage(),'error',true);
            $this->error(__('Network error'));
        }
    }

    /**
     * 技工详情
     * @return void
     */
    public function artificerInfo(){
        try {
            $id = $this->request->post('id/d');
            $model = new Artificer();
            $data = $model->details($id);
            if($data === false){
                $this->error($model->getError());
            }
            $this->success(__('success'),$data);
        }catch (Exception $e){
            Log::write('错误信息：'.$e->getMessage(),'error',true);
            $this->error(__('Network error'));
        }
    }

    /**
     * 援助配置
     * @return void
     */
    public function aidConfig()
    {
        $this->success('success',[
            'initiate_price' => \app\common\model\Config::getValue('initiate_price','assistance'),
            'starting_distance' => \app\common\model\Config::getValue('starting_distance','assistance'),
            'unit_price' => \app\common\model\Config::getValue('unit_price','assistance'),
        ]);
    }

    public function notify(){
        $paytype = $this->request->param('paytype');

        $pay = Service::checkNotify($paytype);
        if (!$pay) {
            echo '签名错误';
            return;
        }
        $data = $pay->verify();
        $payModel = new Pay();
        try {
            //你可以在此编写订单逻辑
            if(($paytype === 'wechat') && ($data['result_code'] == 'SUCCESS') ){
                $payModel->notify($data['out_trade_no'],$data['transaction_id']);
            }elseif (($paytype === 'alipay') && ($data['trade_status'] == 'TRADE_SUCCESS')){
                $payModel->notify($data['out_trade_no'],$data['trade_no']);
            }else{
                Log::write('回调数据：'.var_export($data,true),'log',true);
                throw new Exception('判断错误！');
            }
            if($payModel->hasError()){
                throw new Exception($payModel->getError());
            }
        } catch (Exception $e) {
            Log::write('回调错误：'.$e->getMessage(),'error',true);
            Log::write('回调错误，数据：'.var_export($data,true),'log',true);
        }
        //下面这句必须要执行,且在此之前不能有任何输出
        return $pay->success()->send();
    }

    /**
     * 退款回调
     * @return void
     */
    public function refundNotify(){
        $paytype = $this->request->param('paytype');
        $config = Service::getConfig($paytype);
        $notify = ($paytype== 'wechat') ? \Yansongda\Pay\Pay::wechat($config) : \Yansongda\Pay\Pay::alipay($config);
        if (!$notify) {
            echo '签名错误';
            return;
        }
        $data = $notify->verify(null,true);
        Log::write('退款回调数据：'.var_export($data,true),'log',true);
        try {
            if(($data->return_code == 'SUCCESS') && ($data->refund_status == 'SUCCESS') ){
                $model = new PayRefund();
                $model->notify($data->out_refund_no,$data->refund_id);
                if($model->hasError()){
                    throw new Exception($model->getError());
                }
            }else{
                Log::write('退款失败回调','log',true);
            }
            //你可以在此编写订单逻辑
        } catch (Exception $e) {
            Log::write('回调错误：'.$e->getMessage(),'error',true);
        }
        //下面这句必须要执行,且在此之前不能有任何输出
        return $notify->success()->send();
    }

}
